//
//  LYLCommentListViewController.m
//  ONE
//
//  Created by dllo on 16/6/13.
//  Copyright © 2016年 GroupNine. All rights reserved.
//

#import "LYLCommentListViewController.h"
#import "LFBNetTool.h"
#import "LYLCommentCell.h"
#import <UITableView+FDTemplateLayoutCell.h>
#import "LYLCommentModel.h"
#import "LYLCommentListModel.h"


#import "LYLNoneMessageCell.h"

@interface LYLCommentListViewController ()
{
    // 评论id
    NSString *_itemId;
    // 文章类型
    LYLReadType _readType;
}

/** 头部视图 */
@property (nonatomic, strong) LYLCommonHeaderView *headerView;

/** 尾部视图 */
@property (nonatomic, strong) LYLCommonFooterView *footerView;

/** 评论列表类型 */
@property (nonatomic, assign) LYLCommentListType commentListType;

/** 头部视图类型 */
@property (nonatomic, assign) LYLHeaderViewType headerViewType;

/** 尾部视图类型 */
@property (nonatomic, assign) LYLFooterViewType footerViewType;

/** 行高 */
@property (nonatomic, strong) NSMutableArray *rowHeights;

/** 数据源数组 */
@property (nonatomic, strong) NSMutableArray *dataSource;

/** 评论数 */
@property (nonatomic, assign) NSInteger dataCount;

@end

@implementation LYLCommentListViewController

- (void)dealloc
{
    DDLogDebug(@"%@ - %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _headerView = LYLHeaderViewTypeNone;
        _footerView = LYLFooterViewTypeNone;
    }
    return self;
}

- (instancetype)initWithCommentListType:(LYLCommentListType)commentListType
{
    return [self initWithCommentListType:commentListType headerViewType:LYLHeaderViewTypeNone footerViewType:LYLFooterViewTypeNone];
}

- (instancetype)initWithCommentListType:(LYLCommentListType)commentListType headerViewType:(LYLHeaderViewType)headerViewType footerViewType:(LYLFooterViewType)footerViewType
{
    self = [super init];
    
    if (self) {
        _commentListType = commentListType;
        _headerViewType = headerViewType;
        _footerViewType = footerViewType;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initData];
    [self createCommentLView];
    
    if ([self isCommentListNotInDetail]) {
        switch (_commentListType) {
            case LYLCommentListTypeReadComments:
            case LYLCommentListTypeMusicComments:
            case LYLCommentListTypeMovieComments:
            {
                self.title = @"评论列表";
                break;
            }
            case LYLCommentListTypeMovieStories:
            {
                self.title = @"电影故事";
                break;
            }
            case LYLCommentListTypeMovieReviews:
            {
                self.title = @"评审团短评";
                break;
            }
            default:
                break;
        }
        
        [LYLCommentListViewController myOne_addMJRefreshTo:self.tableView target:self refreshAction:@selector(refresh) loadMoreAction:@selector(loadMore)];
        
        [self getData];
    }
}

#pragma mark --刷新
+ (void)myOne_addMJRefreshTo:(UIScrollView *)scrollView target:(id)target refreshAction:(SEL)refreshAction loadMoreAction:(SEL)loadMoreAction {
    if (refreshAction != nil) {
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:target refreshingAction:refreshAction];
        header.lastUpdatedTimeLabel.hidden = YES;
        header.stateLabel.hidden = YES;
        scrollView.mj_header = header;
    }
    
    if (loadMoreAction != nil) {
        MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:target refreshingAction:loadMoreAction];
        [footer setTitle:@"点击或上拉加载更多" forState:MJRefreshStateIdle];
        //        [footer setTitle:@"松开立即加载更多" forState:MJRefreshStatePulling];
        [footer setTitle:@"正在加载更多的数据..." forState:MJRefreshStateRefreshing];
        [footer setTitle:@"没有更多啦" forState:MJRefreshStateNoMoreData];
        scrollView.mj_footer = footer;
    }
}

#pragma mark --初始化数据
- (void)initData
{
    _rowHeights = @[].mutableCopy;
    _dataSource = @[].mutableCopy;
}

#pragma mark --创建评论视图
- (void)createCommentLView
{
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 60, 0, 0);
    [self.tableView registerClass:[LYLCommentCell class] forCellReuseIdentifier:kLYLCommentCellID];
    [self.tableView registerClass:[LYLNoneMessageCell class] forCellReuseIdentifier:kLYLNoneMessageCellID];
    self.tableView.tableFooterView = [UIView new];
    
    if (![self isCommentListNotInDetail]) {
        __weak typeof(self) weakSelf = self;
        
        _headerView = [[LYLCommonHeaderView alloc] initWithHeaderViewType:_headerViewType];
        _headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, [LYLCommonHeaderView headerViewHeight]);
        _footerView = [[LYLCommonFooterView alloc] initWithFooterViewType:_footerViewType];
        _footerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, [LYLCommonFooterView footerViewHeight]);
        _footerView.showAllItems = ^() {
            [weakSelf showAllItems];
        };
        self.tableView.tableHeaderView = _headerView;
        self.tableView.tableFooterView = _footerView;
        
        self.tableView.scrollsToTop = NO;
        self.tableView.showsVerticalScrollIndicator = NO;
    }
    else
    {
        self.tableView.scrollsToTop = YES;
        self.tableView.showsVerticalScrollIndicator = YES;
    }
}

#pragma mark --设置评论cell
- (void)configureCell:(LYLCommentCell *)cell withModel:(id)model atIndexPath:(NSIndexPath *)indexPath {
    switch (_commentListType) {
        case LYLCommentListTypeReadComments:
        case LYLCommentListTypeMusicComments:
        case LYLCommentListTypeMovieComments: {
            [cell configureCellForCommonWithComment:(LYLCommentModel *)model atIndexPath:indexPath];
            break;
        }
        case LYLCommentListTypeMovieStories: {
//            [cell configureCellForMovieWithStory:(LYLMovieStory *)model atIndexPath:indexPath];
            break;
        }
        case LYLCommentListTypeMovieReviews: {
//            [cell configureCellForMovieWithReview:(LYLMovieReview *)model atIndexPath:indexPath];
            break;
        }
        default:
            break;
    }
}

#pragma mark --显示全部评论
- (void)showAllItems
{
    LYLCommentListViewController *commentListViewController = [[LYLCommentListViewController alloc] initWithCommentListType:_commentListType headerViewType:LYLHeaderViewTypeNone footerViewType:LYLFooterViewTypeNone];
    switch (_commentListType) {
        case LYLCommentListTypeNone:
            break;
        case LYLCommentListTypeReadComments:
        {
            [commentListViewController configureViewForReadDetailWithReadType:_readType itemId:_itemId];
            break;
        }
        case LYLCommentListTypeMusicComments:
        {
            [commentListViewController configureViewForMusicDetailWithItemId:_itemId];
            break;
        }
        case LYLCommentListTypeMovieStories:
        case LYLCommentListTypeMovieReviews:
        case LYLCommentListTypeMovieComments:
        {
            [commentListViewController configureViewForMovieDetailWithItemId:_itemId];
            break;
        }
        default:
            break;
    }
    
    [self.navigationController pushViewController:commentListViewController animated:YES];
}

#pragma mark --评论列表存在
- (BOOL)isCommentListNotInDetail
{
    return (_headerViewType == LYLHeaderViewTypeNone && _footerViewType == LYLFooterViewTypeNone);
}

#pragma mark --计算高度
- (void)calculateHeight
{
    CGFloat tableViewHeight = 0;
    
    if (_dataSource.count > 0) {
        [_rowHeights removeAllObjects];
        
        for (id model in _dataSource) {
            CGFloat cellHeight = [self.tableView fd_heightForCellWithIdentifier:kLYLCommentCellID configuration:^(LYLCommentCell *cell) {
                [self configureCell:cell withModel:model atIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
            }];
            [_rowHeights addObject:@(ceil(cellHeight))];
            tableViewHeight += ceil(cellHeight);
        }
    }
    else
    {
        tableViewHeight += [LYLNoneMessageCell cellHeight];
    }
    
    if (_headerView != LYLHeaderViewTypeNone) {
        tableViewHeight += [LYLCommonHeaderView headerViewHeight];
    }
    
    if (_footerView != LYLFooterViewTypeNone) {
        tableViewHeight += _footerViewType != LYLFooterViewTypeShadow ? [LYLCommonFooterView footerViewHeight] : [LYLCommonFooterView footerViewHeightForShadow];
    }
    
    if (_finishedCalculateHeigt && self.parentViewController) {
        _finishedCalculateHeigt(tableViewHeight);
    }
}

#pragma mark --数据源数组中的最后一项的id
- (NSString *)lastItemIdInDataSource {
    if (_dataSource.count > 0) {
        switch (_commentListType) {
            case LYLCommentListTypeReadComments:
            case LYLCommentListTypeMusicComments:
            case LYLCommentListTypeMovieComments: {
                return ((LYLCommentModel *)[_dataSource lastObject]).id;
            }
            case LYLCommentListTypeMovieStories: {
//                return ((LYLMovieStory *)[_dataSource lastObject]).storyId;
            }
            case LYLCommentListTypeMovieReviews: {
//                return ((LYLMovieReview *)[_dataSource lastObject]).reviewId;
            }
            default:
                return @"0";
        }
    } else {
        return @"0";
    }
}

#pragma mark --更新视图
- (void)updateView
{
    if (![self isCommentListNotInDetail]) {
        [self calculateHeight];
        [_footerView configureViewWithCount:_dataCount];
    }
    
    [self.tableView reloadData];
}

#pragma mark --设置阅读评论视图
- (void)configureViewForReadDetailWithReadType:(LYLReadType)readType itemId:(NSString *)itemId
{
    _itemId = itemId;
    _readType = readType;
}

#pragma mark --设置音乐评论视图
- (void)configureViewForMusicDetailWithItemId:(NSString *)itemId
{
    _itemId = itemId;
}

#pragma mark --设置电影评论视图
- (void)configureViewForMovieDetailWithItemId:(NSString *)itemId
{
    _itemId = itemId;
}

#pragma mark --网络请求
- (void)getData
{
    [self getDataWithFirstItemId:@"0"];
}

- (void)getDataWithFirstItemId:(NSString *)firstItemId
{
    switch (_commentListType) {
        case LYLCommentListTypeReadComments:
        case LYLCommentListTypeMusicComments:
        case LYLCommentListTypeMovieComments:
        {
            [self getCommentDataWithFirstItemId:firstItemId];
            break;
        }
        case LYLCommentListTypeMovieStories:
        {
            
            break;
        }
        case LYLCommentListTypeMovieReviews:
        {
            
            break;
        }
            
        default:
            break;
    }
}

- (void)getCommentDataWithFirstItemId:(NSString *)firstItemId
{
    NSString *apiString;
    if (_commentListType == LYLCommentListTypeReadComments) {
        apiString = [LFBNetTool apiStringForReadWithReadType:_readType];
    } else if (_commentListType == LYLCommentListTypeMusicComments) {
        apiString = LYLApiMusic;
    } else if (_commentListType == LYLCommentListTypeMovieComments) {
        apiString = LYLApiMovie;
    }
    
    if (IsStringEmpty(apiString)) {
        return;
    }
    
    if ([self isCommentListNotInDetail]) {
        [LFBNetTool getNetWithURL:[NSString stringWithFormat:LYLApiGetTimeComments, apiString, _itemId, firstItemId] Body:nil Header:nil Response:LFBJSON Success:^(id result) {
            if ([result[@"res"] integerValue] == 0) {
                NSDictionary *data = result[@"data"];
                LYLCommentListModel *listModel = [[LYLCommentListModel alloc] initWithDic:data];
                _dataCount = listModel.count;
                if ([firstItemId isEqualToString:@"0"]) {
                    [_dataSource removeAllObjects];
                }
                [_dataSource addObjectsFromArray:listModel.data];
                
                if ([self isCommentListNotInDetail]) {
                    [self endRefreshingWithHasMoreData:listModel.data.count >= 20];
                }
                
                [self updateView];
            }
            
        } Failure:^(NSError *error) {
            
        }];
    } else {
        [LFBNetTool getNetWithURL:[NSString stringWithFormat:LYLApiGetPraiseComments, apiString, _itemId, firstItemId] Body:nil Header:nil Response:LFBJSON Success:^(id result) {
            if ([result[@"res"] integerValue] == 0) {
                NSDictionary *data = [result objectForKey:@"data"];
                LYLCommentListModel *listModel = [[LYLCommentListModel alloc] initWithDic:data];
                _dataCount = listModel.count;
                if ([firstItemId isEqualToString:@"0"]) {
                    [_dataSource removeAllObjects];
                }
                [_dataSource addObjectsFromArray:listModel.data];
                
                if ([self isCommentListNotInDetail]) {
                    [self endRefreshingWithHasMoreData:listModel.data.count >= 20];
                }
                
                [self updateView];
            }
        
        } Failure:^(NSError *error) {
            
        }];
    }
}

#pragma mark --刷新
- (void)refresh
{
    [self getData];
}

#pragma mark --加载
- (void)loadMore
{
    [self getDataWithFirstItemId:[self lastItemIdInDataSource]];
}

#pragma mark --结束刷新
- (void)endRefreshingWithHasMoreData:(BOOL)hasMoreData {
    if (self.tableView.mj_header && self.tableView.mj_header.isRefreshing) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer resetNoMoreData];
    }
    
    if (hasMoreData) {
        [self.tableView.mj_footer endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataSource.count == 0 ? 1 : _dataSource.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_dataSource.count == 0) {
        return [tableView dequeueReusableCellWithIdentifier:kLYLNoneMessageCellID];
    }
    
    return [tableView dequeueReusableCellWithIdentifier:kLYLCommentCellID forIndexPath:indexPath];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_dataSource.count == 0) {
        return [LYLNoneMessageCell cellHeight];
    }
    
    if ([self isCommentListNotInDetail]) {
        return [tableView fd_heightForCellWithIdentifier:kLYLCommentCellID cacheByIndexPath:indexPath configuration:^(LYLCommentCell *cell) {
            [self configureCell:cell withModel:_dataSource[indexPath.row] atIndexPath:indexPath];
        }];
    }
    else
    {
        return [_rowHeights[indexPath.row] floatValue];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_dataSource.count == 0) {
        return;
    }
    
    [self configureCell:(LYLCommentCell *)cell withModel:_dataSource[indexPath.row] atIndexPath:indexPath];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
